<?php
declare (strict_types = 1);
namespace app\admin\controller;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Iai\V20200303\IaiClient;

use TencentCloud\Iai\V20200303\Models\DeletePersonRequest;  /** 删除人员 */

use think\Request;
use think\facade\{View, Session, Db};
use think\exception\ValidateException;

use app\admin\validate\UsersValidate;

use app\admin\model\{Users, UserShop, Admin, Star};

class UserController extends BaseController
{
    private $userModel;
    private $token;
    public function __construct(Users $userModel)
    {
        $this->userModel = $userModel;
        $this->token = Session::get('token');
    }

    public function user_list()
    {
        $adminModel = new Admin();

        if($this->token['role_id'] < 2){
            $where = [['role_id', '=', 2]];
        }else{
            $where = ['id' => $this->token['id']];
        }

        $admin_list = $adminModel->getList($where, 0);

        if($admin_list['code'] != 'ok'){
            $admin_list['data'] = [];
        }

        View::assign('token', $this->token['role_id']);
        View::assign('admin_list', $admin_list['data']);
        return view();
    }

    /** 渲染用户编辑页面 */
    public function user_edit(){
        $data = input('');

        $starModel = new Star();
        $userShopModel = new UserShop();

        $where[] = ['s.user_id', '=', $data['id']];
        $where[] = ['s.admin_id', '=', $data['admin_id']];
        $field = 'u.id, u.nickname, s.admin_id, s.money, s.point, s.money_gold, s.card_money, s.star_id';
        $info = $userShopModel->getUserShopShow($where, $field)['data'];

        $info['star_name'] = $starModel->getVal(['id' => $info['star_id']], 'name')['data'];

        $star_list = $starModel->getList([['id', '<>', $info['star_id']]])['data'];

        View::assign('user', $info);
        View::assign('star_list', $star_list);
        return view();
    }

    // 获取用户数据列表
    public function user_data()
    {
        $data = input('get.');

        // 验证数据
        try{
            validate(UsersValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where = [];

        if($this->token['role_id'] == 1){
            $adminModel = new Admin();
            $admin_list = $adminModel->getList(['pid' => $this->token['id']], 'id');

            if($admin_list['code'] == 'ok'){
                $ids = array_column($admin_list['data']->toArray(), 'id');

                $where[] = ['s.admin_id', 'in', $ids];
            }
        }else if($this->token['role_id'] == 2){
            $where[] = ['s.admin_id', '=', $this->token['id']];
        }

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['phone'])){
                $where[] = ['u.phone', 'like', '%' . $data['key']['phone'] . '%'];
            }

            if(!empty($data['key']['nickname'])){
                $where[] = ['u.nickname', 'like', '%' . $data['key']['nickname'] . '%'];
            }

            if(!empty($data['key']['admin_id'])){
                $where[] = ['s.admin_id', '=', $data['key']['admin_id']];
            }
        }

        $userShopModel = new UserShop();

        /** 查询数据总条数 */
        $count = $userShopModel->getUserShopNum($where);

        $field = 'u.id, u.nickname, u.head_img, u.phone, u.unique, u.type, s.admin_id, s.money, s.point, s.money_gold, s.card_money, s.star_id, s.create_time';
        $list = $userShopModel->getUserShopList($where, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['list'], $count);
    }

    // 编辑会员数据
    public function user_edit_data()
    {
        $data = input('post.');

        // 验证数据
        // try{
        //     validate(UsersValidate::class)->scene('edit')->check($data);
        // }catch(ValidateException $e){
        //     $this->error_back($e->getError());
        // }

        $userModel = new Users();
        $userShopModel = new UserShop();
        
        $flag = $userModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $shop_flag = $userShopModel->editWhere(['star_id' => $data['star_id'], 'card_money' => $data['card_money']], ['user_id' => $data['id'], 'admin_id' => $data['admin_id']]);

        $this->success_back('修改成功');
    }

    // 转到员工
    public function rollOut()
    {   
        $userModel = new Users();
        $data = input('post.');

        // 验证数据
        try{
            validate(UsersValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $userInfo = $userModel->getFind(['id' => $data['id']])['data'];

        $data['type'] = 2;
        $data['admin_id'] = $userInfo['bind_admin_id'];

        $flag = $userModel->edit($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('转出成功');
    }

    // 删除用户
    public function user_del()
    {
        $userModel = new Users();
        $data = input('post.');

        // 验证数据
        try{
            validate(UsersValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $userModel->del(['id' => $data['id']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->face_del($data['id']);

        $this->success_back('删除成功');
    }

    /** 删除人员 */
    public function face_del($user_id){
        try{
            $cred = new Credential("AKIDPYWP2P6O1h9MSKtJ6ogTcaKq8KG2DmQs", "Ox73y42ta6J9qPmvxlMIrFd1B6k80e4L");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");
            
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new IaiClient($cred, "ap-beijing", $clientProfile);

            $req = new DeletePersonRequest();
            
            $params = array(
                "Action"     => "DeletePerson",
                "Version"    => "2020-03-03",
                "Region"     => "ap-beijing",
                "GroupId"    => 'face_meiye',
                "PersonId"   => (string)$user_id,
            );

            $req->fromJsonString(json_encode($params));

            $resp = $client->DeletePerson($req);

            /** 接收返回的数据并转数组 */
            $face_data = json_decode($resp->toJsonString(), true);

            $this->success_back('ok', $face_data);
        }catch(TencentCloudSDKException $e){
            $this->success_back('ok', $e);
        }
    }
}
